﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BestPrice.Core.Manager.Implement
{
    using Common;
    public class CategoryManager : Manager<Category, CategoryKey>, ICategoryManager
    {
        public CategoryManager()
        {
        }

        public List<Category> GetAll()
        {
            var ctx = base.Ctx;
            var categoryQuery = from item in ctx.Categories
                                where item.Status == "A"
                                select item;
            var categories = categoryQuery.ToList();

            var webSiteQuery = from item in ctx.WebSites
                               where item.Status == "A"
                               select item;
            var webSites = webSiteQuery.ToList();

            var webSiteCategoryQuery = from item in ctx.WebSiteCategories
                                       where item.Status == "A"
                                       select item;
            var webSiteCategories = webSiteCategoryQuery.ToList();

            var formatterQuery = from item in ctx.Formatters
                                 where item.Status == "A"
                                 select item;
            var formatters = formatterQuery.ToList();


            foreach (var item in webSites)
            {
                item.Formatter = formatters.Where(i => i.WebSiteID == item.ID).FirstOrDefault();
            }

            foreach (var c in categories)
            {
                var wsCsQry = from item in webSiteCategories
                              where item.CategoryID == c.ID
                              select item.WebSiteID;
                var wsCs = wsCsQry.ToList();

                var wsQry = from item in webSites
                            where wsCs.Contains(item.ID)
                            select item;
                var wss = wsQry.ToList();

                c.WebSites = wss;
            }

            return categories;
        }
    }
}
